package com.heima.admin.interceptor;

import com.heima.admin.utils.ThreadLocalUtils;
import com.heima.model.admin.pojos.AdUser;
import com.heima.utils.common.AppJwtUtil;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Optional;

public class AdInterceptor implements HandlerInterceptor {
    /**
     * 请求到达controller方法之前执行
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取请求头中的token,并获取token中的userId
        String token = request.getHeader("token");
        if (token !=null){
            Claims claimsBody = AppJwtUtil.getClaimsBody(token);
            if (claimsBody != null){
                String id = (String) claimsBody.get("id");
                //判断userId是否存在
                Optional<String> optional = Optional.ofNullable(id);
                if (optional.isPresent()){
                    //不为空,则将userId存入threadLocal中
                    AdUser adUser = new AdUser();
                    adUser.setId(Integer.valueOf(id));
                    ThreadLocalUtils.setUser(adUser);
                }
            }
        }

        return true;
    }
    /**
     * 请求执行完controller方法后执行
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        ThreadLocalUtils.removeUser();
    }
}
